package com.cxyw.qqrobot.service;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxyw.qqrobot.domain.SeTu;
import com.cxyw.qqrobot.mapper.SeTuMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
@Slf4j
public class SeTuService {


    @Resource
    SeTuMapper seTuMapper;

    @Value("${seTu.min_num}")
    public int minNum;

    @Value("${seTu.pull_num}")
    public int pullNum;

//    public static String getSeTuApi() {
//        String response = HttpRequest.get("https://image.anosu.top/pixiv/json").execute().body();
//        String url = new JSONArray().parseArray(response).getJSONObject(0).getString("url");
//
//
//        String filename = DigestUtil.md5Hex(url) + ".jpg";
//        File file = new File("img/" + filename);
//        HttpUtil.downloadFile(url, file);
//
//        // 将图片转换为Base64编码
//        byte[] fileBytes = FileUtil.readBytes(file);
//        String base64Image = Base64.encode(fileBytes);
//        System.out.println(base64Image);
//        return base64Image;
//    }


    public String getSeTuByDb() {
        SeTu seTu = seTuMapper.selectOne(new QueryWrapper<SeTu>().eq("status", 0).last("limit 1"));
        if (seTu == null) {
            log.info("数据库中没有涩图了,请等待涩图获取任务执行");
            return null;
        }
        seTu.setStatus(1);
        seTuMapper.updateById(seTu);
        return seTu.getUrl();
    }

    public String getSeTu(){
        long l=System.currentTimeMillis();
        String url = getSeTuApi().get(0);
        String filename = DigestUtil.md5Hex(url) + ".jpg";
        File file = new File("img/" + filename);
        HttpUtil.downloadFile(url, file);
        // 上传图片到阿里云OSS
        String ossUrl = uploadToOSS(file.getPath(), filename);
        log.info("成功获取涩图并上传到OSS:{},ossUrl:{},耗时:{}ms", url,ossUrl,System.currentTimeMillis()-l);
        return ossUrl;
    }

    public String getSeTuByTag(String tag){
        long l=System.currentTimeMillis();
        String url = getSeTuByTagApi(tag).get(0);
        String filename = DigestUtil.md5Hex(url) + ".jpg";
        File file = new File("img/" + filename);
        HttpUtil.downloadFile(url, file);
        // 上传图片到阿里云OSS
        String ossUrl = uploadToOSS(file.getPath(), filename);
        log.info("成功获取涩图并上传到OSS:{},ossUrl:{},耗时:{}ms", url,ossUrl,System.currentTimeMillis()-l);
        return ossUrl;
    }


    public List<String> getSeTuApi() {
        String response = HttpRequest.get("https://image.anosu.top/pixiv/json?num=" + pullNum).execute().body();
        LinkedList<String> urls = new LinkedList<>();
        new JSONArray().parseArray(response).forEach(item -> {
            String url = ((JSONObject) item).getString("url");
            urls.add(url);
        });
        return urls;
    }

    public List<String> getSeTuByTagApi(String tag) {
        String response = HttpRequest.get("https://image.anosu.top/pixiv/json?num=" + pullNum+"&keyword="+tag).execute().body();
        LinkedList<String> urls = new LinkedList<>();
        new JSONArray().parseArray(response).forEach(item -> {
            String url = ((JSONObject) item).getString("url");
            urls.add(url);
        });
        return urls;
    }


    static String endpoint = "";
    static String accessKeyId = "";
    static String accessKeySecret = "";
    static String bucketName = "";

    public static String uploadToOSS(String localFilePath, String targetFileName) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件
        ossClient.putObject(bucketName, targetFileName, new File(localFilePath));
        // 设置URL过期时间为10年
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, targetFileName, expiration);
        // 关闭OSSClient
        ossClient.shutdown();
        return url.toString();
    }


    //每10s执行一次 当se_tu数量小于minNum时执行,再获取pullNum个涩图
    @Scheduled(cron = "0/10 * * * * ?")
    public void collectSeTu() throws Exception {
        int count = seTuMapper.selectCount(new QueryWrapper<SeTu>().eq("status", 0));
        if (count >= minNum) {
            return;
        }
        List<String> seTuApi = getSeTuApi();
        for (String url : seTuApi) {
            try {
                String filename = DigestUtil.md5Hex(url) + ".jpg";
                File file = new File("img/" + filename);
                HttpUtil.downloadFile(url, file);
                // 上传图片到阿里云OSS
                String ossUrl = uploadToOSS(file.getPath(), filename);
                seTuMapper.insert(new SeTu(ossUrl, 0));
                log.info("成功获取涩图并以插入数据库:{},ossUrl:{}", url,ossUrl);
            } catch (Exception e) {
                log.error("获取一条涩图失败:{},跳过该涩图的获取,该涩图url:{}", e.getMessage(), url);
            }
            Thread.sleep(2000);
        }
        log.info("成功获取{}条涩图并存入库中", seTuApi.size());
    }



    @Value("${qqrobot.proxy.ip}")
    public String httpProxyIp;

    @Value("${qqrobot.proxy.port}")
    public int httpProxyPort;

    @PostConstruct
    public void httpProxy(){

//        log.info("开启代理成功,ip:{},port:{}",httpProxyIp,httpProxyPort);
    }
}
